package org.hoemwork.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.hoemwork.datasouce.MyRoutingDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class Config {

    /**
     定义数据源1
     **/
    @Bean(name = "dataSource1")
    public DataSource  dataSource1() {
        DruidDataSource  druidDataSource = new DruidDataSource();
      druidDataSource.setUsername("root");
      druidDataSource.setPassword("root");
      druidDataSource.setUrl("jdbc:mysql://10.10.60.111:3306/test?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false");
      druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        return druidDataSource;
    }

    /**
     定义数据源2
     **/
    @Bean(name = "dataSource2")
    public DataSource dataSource2() {
        DruidDataSource  druidDataSource = new DruidDataSource();
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("root");
        druidDataSource.setUrl("jdbc:mysql://10.10.60.111:3306/test?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false");
        druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        return druidDataSource;
    }

    /**
     定义MyRoutingDataSource
     **/
    @Bean(name = "myRoutingDataSource")
    public MyRoutingDataSource myRoutingDataSource() {
        Map<Object, Object> map =new HashMap<Object, Object>(2);
        map.put(1,dataSource1());
        map.put(2,dataSource2());
        MyRoutingDataSource m=new MyRoutingDataSource(dataSource1() ,map);
        return m;
    }

    /**
     定义一个spring提供的数据库操作类，我测试sql用的，实际要定义mybaties配置把数据源配置给它
     **/
    @Bean
    public JdbcTemplate jdbcTemplate() {
        JdbcTemplate j=new JdbcTemplate();
        j.setDataSource(myRoutingDataSource());
        return j;
    }
}

